package com.wlz.reconnect;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wlz
 * @date 2022-07-09  5:19 下午
 */
@Slf4j
public class ReconnectNettyClientHandler extends SimpleChannelInboundHandler<String> {

    private ReconnectNettyClient reconnectNettyClient;

    public ReconnectNettyClientHandler(ReconnectNettyClient reconnectNettyClient) {
        this.reconnectNettyClient = reconnectNettyClient;
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("helloserver".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(buf);
    }



    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        log.info(" 收到服务端的消息: {} ", s);
        log.info(" 服务端的地址为:  {} ", ctx.channel().remoteAddress());
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info(" 运行中断开重连 。。。。。 ");
        reconnectNettyClient.connect();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
